// check point:
// line39: all thread share file discriptor

// keypoint: a process can only hold limit file discriptor,
// so pipe should be close at once all data read out
#include "kernel/types.h"
#include "user/user.h"

int dump(int fd)
{
    int pri;
    int buf;
    int p[2];
    pipe(p);
    if(read(fd, &pri, sizeof(int)) == 0)
      return 0;
    printf("prime %d\n", pri);
    while(read(fd, &buf, sizeof(int)) != 0) {
      if(buf % pri != 0) {
        write(p[1], &buf, sizeof(int));
      }
      //else drop it;
    }
    int pid = fork();
    if (pid == 0) {
      close(p[1]);
      dump(p[0]);
      close(p[0]);
    } else {
      close(p[1]);
      close(p[0]);
      wait(0);
    }
    return 0;
}

int
main(int *argc, char *argv[])
{
  int p[2];
  pipe(p);
  for (int i = 2; i<=35; i++) {
      write(p[1], &i, sizeof(int));
  }
  close(p[1]);
  dump(p[0]);
  close(p[0]);
  exit(0); //NOTE: return 0; will lead wired usertrap error
}

